﻿using System;
using System.Collections.Generic;
using System.Net;
using System.ServiceModel.DomainServices.Client;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using DomainDriver.Presentation.Silverlight.Base;
using AutomotivePricingModel.Companies;
using AutomotivePricingSilverlightApp.Web.Services;

namespace AutomotivePricingSilverlightApp.Controls.Companies
{
    public class CompanyEditorController : CompanyListController
    {
        public override bool IsReadyToDisplay
        {
            get { return (GetSelectedCompany() != null); }
        }

        public void UpdateCompanyName(string companyName)
        {
            Company company = GetSelectedCompany();
            CompaniesDomainContext companiesContext = new CompaniesDomainContext();
            EntityQuery<Company> updateNameQuery = companiesContext.UpdateCompanyNameQuery(company.EF_Id, companyName);
            m_Operation = companiesContext.Load<Company>(updateNameQuery);
            m_Operation.Completed += new EventHandler(m_Operation_Completed);
        }

        public void UpdateCeoName(string ceoName)
        {
            Company company = GetSelectedCompany();
            CompaniesDomainContext companiesContext = new CompaniesDomainContext();
            EntityQuery<Company> updateNameQuery = companiesContext.UpdateCeoNameQuery(company.EF_Id, ceoName);
            m_Operation = companiesContext.Load<Company>(updateNameQuery);
            m_Operation.Completed += new EventHandler(m_Operation_Completed);
        }

        private LoadOperation<Company> m_Operation = null;
        private void m_Operation_Completed(object sender, EventArgs e)
        {
            List<Company> companies = new List<Company>(m_Operation.Entities);
            if (companies.Count < 1)
            { return; }

            Company company = companies[0];
            SetSelectedCompany(company);

            DispatchRefreshRequestedEvent();
        }
    }
}